<?php

    /**
     * SynergyConfiguration.php (Singleton)
     *
     * This class holds the configurations used by Synergy
     **/

    class SynergyConfiguration {

        private static $_instance   = null;
        private $_map               = null;

        /**
         * Constructor attempts to restore the map from cache
         * before resorting to reparsing the XML definition.
         **/
        private function __construct() {

			$this->_buildFromXML();

        }

        /**
         * Prevent _clone(...) from being called.
         **/
        private function __clone() {}

        /**
         * Returns the static instance of this Singleton, creating
		 * one if required.
         **/
        public static function getInstance() {

            if(!self::$_instance) {
                self::$_instance = new SynergyConfiguration();
            }

            return self::$_instance;

		}

		/**
		 * Returns value for a specific configuration key
		 **/
		public function get($key) {

			if(isset($this->_map[$key])) {
				return $this->_map[$key];
			} else {
				error_log("[SYNERGY - NOTICE] : Undefined setting ($key) accessed");
				return "";
			}

		}

		/**
		 * Parses XML definition of configuration.
         **/
        private function _buildFromXML() {

			if(!file_exists(BASE_PATH . "configs/settings.xml")) {
				error_log("[SYNERGY - ERROR] : Configuration file not found");
				exit;
			}

			$xmlContent	= file_get_contents(BASE_PATH . "configs/settings.xml");
			
			try {
				$xmlObj	= new SimpleXMLElement($xmlContent);
			} catch(Exception $e) {
				error_log("[SYNERGY - ERROR] : Failed to process XML");	
			}

			$this->_processXML($xmlObj);

        }

		/**
		 * Recursive function to process and store configurations.
         **/
        private function _processXML($branch, $stack = "") {

			if(strlen($stack) > 0) { $stack .= "."; }

			foreach($branch->children() as $definition => $value) {
				if(count($value->children()) > 0) {
					$this->_processXML($value,$stack.$definition);
				} else {
					$this->_map[ $stack . $definition ] = (String) $value;
				}
			}

		}

	}

?>
